package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.Xtree;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.YtendereqeMapper;
import com.ruoyi.system.domain.Ytendereqe;
import com.ruoyi.system.service.IYtendereqeService;
import com.ruoyi.common.core.text.Convert;

/**
 * 招标需求Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-03
 */
@Service
public class YtendereqeServiceImpl implements IYtendereqeService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YtendereqeMapper ytendereqeMapper;

    /**
     * 查询招标需求
     *
     * @param id 招标需求主键
     * @return 招标需求
     */
    @Override
    public Ytendereqe selectYtendereqeById(String id)
    {
        return ytendereqeMapper.selectYtendereqeById(id);
    }

    public List<Ytendereqe> selectYtendereqeByIds(String [] ids)
    {
        return ytendereqeMapper.selectYtendereqeByIds(ids);
    }

    /**
     * 查询招标需求列表
     *
     * @param ytendereqe 招标需求
     * @return 招标需求
     */
    @Override
    @DataScope(deptAlias = "d",userAlias = "u")
    public List<Ytendereqe> selectYtendereqeList(Ytendereqe ytendereqe)
    {
        List<Ytendereqe> ytenList=ytendereqeMapper.selectYtendereqeList(ytendereqe);
//        for (Ytendereqe yten:
//        ytenList) {
//            List<Ytendereqe> ytenRankList = ytendereqeMapper.selectYrank(yten);
//            if(ytenRankList !=null && ytenRankList.size()>0){
//                for (Ytendereqe ytenRank:
//                ytenRankList) {
//                    if(yten.getYpri0()!=null && ytenRank.getYpri0()!=null && ytenRank.getYpri0().compareTo(yten.getYpri0())==0){
//                        yten.setYrank(ytenRank.getYrank());
//                        break;
//                    }
//                }
//            }
//        }

        return ytenList;
    }
    @Override

    public List<Ytendereqe> selectYtendereqdList(Ytendereqe ytendereqe)
    {
        List<Ytendereqe> ytenList=ytendereqeMapper.selectYtendereqdList(ytendereqe);
        return ytenList;
    }
    /**
     * 新增招标需求
     *
     * @param ytendereqe 招标需求
     * @return 结果
     */
    @Override
    public int insertYtendereqe(Ytendereqe ytendereqe)
    {
        return ytendereqeMapper.insertYtendereqe(ytendereqe);
    }

    /**
     * 修改招标需求
     *
     * @param ytendereqe 招标需求
     * @return 结果
     */
    @Override
    public int updateYtendereqe(Ytendereqe ytendereqe)
    {
        Ytendereqe newYten = new Ytendereqe();
        Ytendereqe old = ytendereqeMapper.selectYtendereqeById(ytendereqe.getId());
        try {
            newYten.setId(ytendereqe.getId());
            newYten.setYghcc(ytendereqe.getYghcc());
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 定义时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
            // 格式化输出
            String formattedDateTime = now.format(formatter);

            if (old == null) {
                throw new Exception("招标单不存在:" + ytendereqe.getId());
            }
            if(ytendereqe.getYpri0().compareTo(new BigDecimal(0))<=0){
                throw new Exception("报价必须>0");
            }
            newYten.setYpri0(ytendereqe.getYpri0());
            newYten.setYzamt(ytendereqe.getYzamt());
            if (StringUtils.isBlank(old.getYdat10())) {
                newYten.setYdat10(formattedDateTime);
                newYten.setYpri10(ytendereqe.getYpri0());
            }
            if (StringUtils.isBlank(old.getYdat20()) && StringUtils.isNotBlank(old.getYdat10())) {
                newYten.setYdat20(formattedDateTime);
                newYten.setYpri20(ytendereqe.getYpri0());
            }

        }catch (Exception e){
            logger.error("招标修改错误:" + e.getMessage());
        }
        int res = ytendereqeMapper.updateYtendereqe(newYten);
        //排名
        getYrank(old);
        return res;
    }

    /**
     * 批量删除招标需求
     *
     * @param updtick0s 需要删除的招标需求主键
     * @return 结果
     */
    @Override
    public int deleteYtendereqeByUpdtick0s(String updtick0s)
    {
        return ytendereqeMapper.deleteYtendereqeByUpdtick0s(Convert.toStrArray(updtick0s));
    }

    /**
     * 删除招标需求信息
     *
     * @param updtick0 招标需求主键
     * @return 结果
     */
    @Override
    public int deleteYtendereqeByUpdtick0(Long updtick0)
    {
        return ytendereqeMapper.deleteYtendereqeByUpdtick0(updtick0);
    }

    /**
    * @Description: 查询各状态数量
    * @author: adam
    * @date: 2024/4/7 11:31
    * @param ytendereqe:
    * @Return: com.ruoyi.system.domain.Ytendereqe
    */
    @Override
    @DataScope(deptAlias = "d",userAlias = "u")
    public Ytendereqe selectYtendereqeCount(Ytendereqe ytendereqe)
    {
        return ytendereqeMapper.selectYtendereqeCount(ytendereqe);
    }

    /**
    * @Description: 导入数据
    * @author: adam
    * @date: 2024/5/10 9:53
    * @param list:
    * @param updateSupport:
    * @Return: java.lang.String
    */
    @Override
    public String importYtende(List<Ytendereqe> list, boolean updateSupport) {

        if (com.ruoyi.common.utils.StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Ytendereqe ytende : list)
        {
            if(ytende.getId().contains("填表说明")){
                break;
            }
            try
            {
                // 查询记录
                Ytendereqe u = ytendereqeMapper.selectYtendereqeById(ytende.getId());
                if (com.ruoyi.common.utils.StringUtils.isNull(u))
                {
                    failureNum++;
                    failureMsg.append("<br/>"+ failureNum + "、单号 " + ytende.getId() + " 不存在");
                }
                else if (u.getYstat0().compareTo(2l)>0)
                {
                    failureNum++;
                    failureMsg.append("<br/>"+ failureNum + "、单号 " + ytende.getId() + " 已完成或已关闭");

                }
                else if (StringUtils.isNotBlank(u.getYdat20()))
                {
                    failureNum++;
                    failureMsg.append("<br/>"+ failureNum + "、单号 " + ytende.getId() + " 已报价2次，不能再操作");

                }
                else if (ytende.getYpri0().compareTo(new BigDecimal(0))<=0)
                {
                    failureNum++;
                    failureMsg.append("<br/>"+ failureNum + "、单号 " + ytende.getId() + " 报价必须大于0");
                }
                else
                {
                    // 获取当前时间
                    LocalDateTime now = LocalDateTime.now();
                    // 定义时间格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
                    // 格式化输出
                    String formattedDateTime = now.format(formatter);

                    Ytendereqe yte = new Ytendereqe();
                    if(StringUtils.isNotBlank(u.getYdat10())){//第二次报价
                        yte.setYdat20(formattedDateTime);
                    }else {
                        yte.setYdat10(formattedDateTime);
                    }
                    yte.setYpri0(ytende.getYpri0());
                    yte.setId(ytende.getId());
                    yte.setYzamt(u.getYqty().multiply(yte.getYpri0()));
                    yte.setYghcc(ytende.getYghcc());
                    ytendereqeMapper.updateYtendereqe(yte);
                    //排名
                    getYrank(u);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、单号 " + ytende.getId() + " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                logger.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "成功"+successNum+"，失败 " + failureNum + "，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public void getYrank(Ytendereqe ytendereqe) {
        List<Ytendereqe> ybpsList = ytendereqeMapper.selectBpsAmt(ytendereqe);
        int i=0;
        for (Ytendereqe ybps: ybpsList) {
            Ytendereqe ytbps = ytendereqeMapper.selectBps(ybps);
            i+=1;
            ytbps.setYzamt(ybps.getYzamt());
            if(StringUtils.isBlank(ytbps.getYrank()) || Integer.parseInt(ytbps.getYrank())!=i){
                ytbps.setYchran(2l);
                ytbps.setYrank(i+"");
            }
            ytendereqeMapper.updateYtendereqm(ytbps);
        }
        /*
        logger.info("价格排名更新:" + ytendereqe.getYnum0());
        Ytendereqe ytend = new Ytendereqe();
        ytend.setYnum0(ytendereqe.getYnum0());
        ytend.setYitm0(ytendereqe.getYitm0());
        List<Ytendereqe> ytendList = ytendereqeMapper.selectYtendereqeYrank(ytend);
        int i=0;
        if(ytendList!=null){
            for (Ytendereqe y:ytendList) {
                i+=1;
                if(StringUtils.isBlank(y.getYrank()) || Integer.parseInt(y.getYrank())!=i){
                    Ytendereqe yup = new Ytendereqe();
                    yup.setYchran(2l);
                    yup.setYrank(i+"");
                    yup.setId(y.getId());
                    ytendereqeMapper.updateYtendereqe(yup);
                }
            }
        }*/
    }

    @Override
    public List<Ytendereqe> selectBpsAmt(Ytendereqe ytendereqe){
        return ytendereqeMapper.selectBpsAmt(ytendereqe);
    };

    @Override
    public List<Ytendereqe> selectInit(Ytendereqe ytendereqe){
        return ytendereqeMapper.selectInit(ytendereqe);
    };

    @Override
    public List<Ytendereqe> selectInitBlob(Ytendereqe ytendereqe){
        return ytendereqeMapper.selectInitBlob(ytendereqe);
    };

    /**
     * 查询招标需求树
     *
     * @param ytendereqe
     * @return
     */
    @Override
    @DataScope(deptAlias = "d",userAlias = "u")
    public List<Xtree> selectYtrqTree(Ytendereqe ytendereqe)
    {
        List<Ytendereqe> ytrqtList = ytendereqeMapper.selectYtrqTreeList(ytendereqe);
        List<Xtree> xtrees = initXtree(ytrqtList);
        return xtrees;
    }

    /**
     * 对象转招标需求树
     *
     * @param ytrqList 招标需求列表
     * @return 树结构列表
     */
    public List<Xtree> initXtree(List<Ytendereqe> ytrqList)
    {
        return initXtree(ytrqList, null);
    }

    /**
     * 对象转招标需求树
     *
     * @param ytrqList 招标需求列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Xtree> initXtree(List<Ytendereqe> ytrqList, List<String> roleDeptList)
    {

        List<Xtree> xtrees = new ArrayList<Xtree>();
        boolean isCheck = com.ruoyi.common.utils.StringUtils.isNotNull(roleDeptList);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        for (Ytendereqe ytrq : ytrqList)
        {
            Xtree xtree = new Xtree();
            xtree.setId(ytrq.getId());
            xtree.setpId(ytrq.getYaprentid());
            xtree.setName(ytrq.getYtreename());
            xtree.setTitle(ytrq.getYtreename());
                if (isCheck)
                {
//                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                xtrees.add(xtree);
        }

        return xtrees;
    }
}
